package com.breeze.webview.webclient;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;

import com.breeze.base.BaseApplication;
import com.breeze.webview.ICommandInterface;
import com.breeze.webview.IWebViewProcessCallbackInterface;
import com.breeze.webview.callbacks.NativeToJSCallback;
import com.breeze.webview.mainprocess.MainProcessCommandService;

/**
 * 负责跨进程执行html到native发送的命令
 */
public class WebViewProcessCommandDispatcher implements ServiceConnection {
    private static WebViewProcessCommandDispatcher sInstance;
    private ICommandInterface mCommandService;

    public static WebViewProcessCommandDispatcher getInstance() {
        if (sInstance == null) {
            sInstance = new WebViewProcessCommandDispatcher();
        }
        return sInstance;
    }

    public void initCommandConnection() {
        Intent intent = new Intent(BaseApplication.sApplication, MainProcessCommandService.class);
        BaseApplication.sApplication.bindService(intent, this, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        // 得到服务端代理对象
        mCommandService = ICommandInterface.Stub.asInterface(service);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        mCommandService = null;
    }

    public void executeCommand(String command, String params, final NativeToJSCallback callback) {
        if (mCommandService != null) {
            try {
                // IPC调用到主进程
                mCommandService.executeCommand(command, params, new IWebViewProcessCallbackInterface.Stub() {
                    @Override
                    public void onResult(String callbackName, String response) throws RemoteException {
                        callback.handleCallback(callbackName, response);
                    }
                });
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }
}
